<?php

namespace Biz\tools;


use Doraemon\tools\Curl;
use Doraemon\tools\Log;
use GuzzleHttp\Psr7\Uri;

class Tbk3rd
{
    const APIKEY = 'DMCFCUbhdc';
    const UID = '2201197800829';

    const URL_TBK_PRIVILEGE_GET = 'https://api.taokouling.com/tkl/TbkPrivilegeGet';
    const URL_TBK_TKL_DECRYPT = 'https://api.taokouling.com/tkl/tkljm';

    public static function tbkPrivilegeGet($itemId)
    {
        $result = Curl::Request('POST', self::URL_TBK_PRIVILEGE_GET, [
            'form_params' => [
                'apikey' => self::APIKEY,
                'itemid' => $itemId,
                'siteid' => TbkUnion::SITE_ID,
                'adzoneid' => TbkUnion::ADZONE_ID,
                'uid' => self::UID
            ]
        ]);
        if (isset($result['json']['result'])) {
            $urlMaker = new Uri($result['json']['result']['data']['item_url']);
            $urlMaker = $urlMaker->withScheme('');
            return (string)$urlMaker;
        } else {
            $msg = isset($result['json']['msg']) ? $result['json']['msg'] : '';
            if ($msg && strpos($msg, '授权') !== false) {
                Log::debug('tbkPrivilegeGet error', $itemId, $result);
                try {
                    Mail::send('tangyiwan@haohaozhu.com', 'tbkPrivilegeGet error#' . $itemId, json_encode($result, JSON_UNESCAPED_UNICODE));
                } catch (\Exception $e) {
                    Log::error($e->getMessage());
                }
            }
            return '';
        }
    }

    public static function tklDecrypt($content)
    {
        $result = Curl::Request('POST', self::URL_TBK_TKL_DECRYPT, [
            'form_params' => [
                'apikey' => self::APIKEY,
                'tkl' => $content
            ]
        ]);
        if (isset($result['json']) && $result['json']['code'] == 1) {
            return $result['json']['url'];
        } else {
            return false;
        }
    }

}